<?php

namespace Plu\qdh\Services;

use Plu\qdh\Services\ServiceBase;
use Plu\qdh\Services\ProductService;
use Plu\qdh\Services\ReportService;
use Httpful\Request;

class ThirdService extends ServiceBase {

    const BASE_API = 'api/list.jsp?custId='.\ThridPart::CUST_ID.'&apikey='.\ThridPart::API_KEY;

    const API_KEY = 'custId='.\ThridPart::CUST_ID.'&apikey='.\ThridPart::API_KEY;

    // 订单号
    private $_productNo;
    // 游玩日期
    private $_traveDate;
    // 关键字
    private $_keyWord;
    // 三方错误信息
    private $_cancelMsg;

    public function setKeyWord($keyWord) {
        $this->_keyWord = $keyWord;
    }

    public function setProductNo($productNo) {
        $this->_productNo = $productNo;
    }

    public function setTravelDate($traveDate) {
        $this->_traveDate = $traveDate;
    }

    // 获取第三方分销系统票项
    public function getThridAllProduction($page) : array {

        $api = self::BASE_API.'&treeId=0&pageNo='.$page.'&pageNum=20';
        $requestUrl = \ThridPart::THRID_URL.$api;
        if ($this->_keyWord) {
            $requestUrl = $requestUrl."&keyWrod=".$this->_keyWord;
        }

        $request    = Request::get($requestUrl)->expectsXml()->send();
        
        if ($request) {  
            $resBody    = $request->body;
            $products   = $resBody->products;
            $totalCount = (string) $resBody->totalNum;
            $resData = [];

            foreach ($products->product as $value) {
                $description = (string) $value->orderDesc;
                $r = [
                    // 产品编号
                    'productNo'       => (string)$value->productNo,
                    // 产品名称
                    'productName'     => (string)$value->productName,
                    // 零售价
                    'salePrice'       => (string)$value->salePrice,
                    // 分销价
                    'SettlementPrice' => (string)$value->SettlementPrice,
                    // 描述
                    'description'     => strip_tags($description),
                    // 景区
                    'viewName'        => (string)$value->viewName,
                    // 城市
                    'cityName'        => (string)$value->cityName,
                    // 开始售票时间
                    'priceStartDate'  => (string)$value->priceStartDate,
                    // 售票结束时间
                    'priceEndDate'    => (string)$value->priceEndDate
                ];
                $resData[] = $r;
            }

            return [$totalCount, $resData];
        }

        return [0, []];
    }

    // 产品详情
    public function getProductDetail() {
        $productNo = $this->_productNo;
        $api = \ThridPart::THRID_URL.'api/detail.jsp?'.self::API_KEY.'&productNo=%s';
        $requestUrl = sprintf($api, $productNo);
        $request    = Request::get($requestUrl)->expectsXml()->send();
        if ($request) {
            $resBody   = $request->body->product;
            $orderDesc = (string) $resBody->orderDesc;
            $response = [
                // 产品图片
                'img'         => (string) $resBody->img,
                // 商品编号
                'productNo'   => (string) $resBody->productNo,
                // 是否需要人工审核
                'is_confirm'  => (string) $resBody->is_confirm,
                // 商品名称
                'productName' => (string) $resBody->productName,
                // 零售价
                'salePrice'   => (string) $resBody->salePrice,
                // 分销价
                'SettlementPrice' => (string)$resBody->SettlementPrice,
                // 几点之前预定
                'startTime'   => (string) $resBody->startTime,
                // 预定后多少分钟生效
                'startMinute' => (string) $resBody->startMinute,
                // 多少分钟不支付自动取消
                'payMinute'   => (string) $resBody->payMinute,
                // 在游玩日期前多少天可退款
                'cancelDay'   => (string) $resBody->cancelDay,
                // 预定说明
                'orderDesc'   => strip_tags($orderDesc),
                // 费用包含
                'charge_include' => (string) $resBody->charge_include,
                // 退款说明
                'refund_note' => (string) $resBody->refund_note,
                // 重要说明
                'important_note' => (string) $resBody->important_note

            ];
            return $response;
        }
        return [];
    }

    // 价格日历表
    public function getProductDaliyInfo() {
        $productNo = $this->_productNo;
        $api = \ThridPart::THRID_URL.'/api/price.jsp?'.self::API_KEY.'&productNo=%s';
        $requestUrl = sprintf($api, $productNo);
        $request = Request::get($requestUrl)->expectsXml()->send();
        $results = $request->body->prices->price;

        if ($results) {
            $productService = new ProductService;
            $productInfo    = $productService->getProductDetail($productNo);
            $format = [];
            if ($productInfo) {
                foreach ($results as $result) {
                    $r = [
                        // 日期
                        'date' => (string) $result->date,
                        // 自定义价格
                        'customPrize' => $productInfo['customPrize'],
                        'marketPrice' => (string) $result->marketPrice,
                        'salePrice'   => (string) $result->salePrice,
                        'remainNum'   => (string) $result->remainNum
                    ];
                    $format[] = $r;
                }
            }
            
            return $format;
        }
        return [];

    }

    // 下单
    public function saveOrder($travateDate, $linkData, $num) {
        $api = \ThridPart::THRID_URL.'api/order.jsp?'.self::API_KEY;
    
        $custId = \ThridPart::CUST_ID;
        $params = "<order>".
                  "<travel_date>".$travateDate."</travel_date>".
                  "<info_id>".$this->_productNo."</info_id>".
                  "<cust_id>$custId</cust_id>".
                  "<num>".$num."</num>".
                  "<link_man>".$linkData['linkMan']."</link_man>".
                  "<link_phone>".$linkData['linkPhone']."</link_phone>".
                  "</order>";

        $requestUrl = $api."&param=".$params;
        $request = Request::get($requestUrl)->expectsXml()->send();
        $resBody = $request->body;
        $status  = (string)$resBody->status;
        $orderId = '0';
        if ($status == \OrderConst::THRID_RESULT_STATUS['success']) {
            $orderId   = (string)$resBody->order_id;
            $orderSate = (string)$resBody->order_state;
            $msg = (string)$resBody->msg;

        } else {
            $msg = (string)$resBody->error_msg;
        }
        return [
            'status'  => (int)$status,
            'orderId' => $orderId, 
            'msg'     => $msg
        ];
    }

    // 第三方付款
    public function peyOrder($orderObj) {
        $orderId    = $orderObj->orderId;
        $requestUrl = \ThridPart::THRID_URL.'api/pay.jsp?'.self::API_KEY.'&orderId='.$orderId;
        $request    = Request::get($requestUrl)->expectsXml()->send();
        $resBody    = $request->body;
        $status     = (string)$resBody->status;
        if ($status == \ThridPart::THRID_CODE['success']) {
            $reportService = new ReportService;
            $reportService->payOrderReport($orderObj);
        } else {
            $orderObj->status = \OrderConst::ORDER_STATUS['applyRejected'];
        }
        if ($orderObj->save()) {
            return true;
        }
        return false;
    }

    // 取消订单
    public function cancelOrder($orderId) {
        $requestUrl = \ThridPart::THRID_URL.'api/cancelOrder.jsp?'.self::API_KEY.'&orderId='.$orderId;
        $request    = Request::get($requestUrl)->expectsXml()->send();
        $resBody    = $request->body;
        $status     = (string)$resBody->status;
        if ($status == 1) {
            return true;
        }
        $this->_cancelMsg = (string)$resBody->error_msg;
        return false;
    }

    // 订单退款
    public function reFindOrder($orderId) {
        $requestUrl = \ThridPart::THRID_URL.'api/changeApplyOrder.jsp?'.self::API_KEY.'&orderId='.$orderId;
        $request    = Request::get($requestUrl)->expectsXml()->send();
        $resBody    = $request->body;
        $status     = (string)$resBody->status;
        if ($status == 1) {
            return true;
        }
        $this->_cancelMsg = (string)$resBody->error_msg;
        return false;
    }

    public function getErrMsg() {
        return $this->_cancelMsg;
    }

 
    
}